package com.msmall.community.tag;

import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.msmall.base.message.Message;
import com.msmall.base.message.MessageManager;
import com.msmall.base.util.Constants;


public class MessageTag extends TagSupport{

	private static final long serialVersionUID = 1789753724652018254L;
	
	private static final Log logger = LogFactory.getLog(MessageTag.class);
	
	private String position;
	
	private boolean clear;
	
	public int doStartTag() throws JspException {
		return (SKIP_BODY);
	}

	public int doEndTag() throws JspException {
		JspWriter writer = pageContext.getOut();
		HttpServletRequest req = (HttpServletRequest) super.pageContext.getRequest();
		HttpSession session = req.getSession();
		String info = "";
		try{
			Long userid = (Long) session.getAttribute(Constants.SESSION_USER_ID_KEY);
			Map<String, Message> messages = MessageManager.getMessages(userid);
			if(messages != null && !messages.isEmpty()){
				if(null != position && !"".equals(position)){
					Message message = messages.get(position);
					if(message != null){
						info = message.getMessage();
					}
				}else{
					Iterator it = messages.keySet().iterator();
					StringBuffer buffer = new StringBuffer();
					while(it.hasNext()){
						buffer.append(((Message)it.next()).getMessage()).append("<br/>");
					}
					info = buffer.substring(0, buffer.lastIndexOf("<br/>"));
				}
			}
			writer.print(info);
			if(clear){
				MessageManager.clearMessages(userid);
			}
		}catch(Exception e){
			
		}
		return (SKIP_BODY);
	}

	public boolean isClear() {
		return clear;
	}

	public void setClear(boolean clear) {
		this.clear = clear;
	}

	public String getPosition() {
		return position;
	}

	public void setPosition(String position) {
		this.position = position;
	}
}
